import { defineStore } from 'pinia'
import { store } from '@/store'
// @ts-expect-error
import { DictDataVO } from '@/api/system/dict/types'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'

const { wsCache } = useCache('sessionStorage')
import { getSimpleDictDataList } from '@/api/system/dict/dict.data'

export interface DictState {
  dictMap: Map<string, any>
  isSetDict: boolean
}

export const useDictStore = defineStore('dict', {
  state: (): DictState => ({
    dictMap: new Map<string, any>(),
    isSetDict: false
  }),
  getters: {
    getDictMap(): Recordable {
      const dictMap = wsCache.get(CACHE_KEY.DICT_CACHE)
      if (dictMap) {
        this.dictMap = dictMap
      }
      return this.dictMap
    },
    getIsSetDict(): boolean {
      return this.isSetDict
    }
  },
  actions: {
    async loadDictData() {
      let res = []
      try {
        res = await getSimpleDictDataList()
      } catch (error) {
        console.warn('从远程获取字典数据失败', error)
      }
      // 设置数据
      const dictDataMap = new Map<string, any>()
      res.forEach((dictData: DictDataVO) => {
        // 获得 dictType 层级
        const enumValueObj = dictDataMap[dictData.dictType]
        if (!enumValueObj) {
          dictDataMap[dictData.dictType] = []
        }
        // 处理 dictValue 层级
        dictDataMap[dictData.dictType].push({
          value: dictData.value,
          label: dictData.label,
          colorType: dictData.colorType,
          cssClass: dictData.cssClass
        })
      })
      this.dictMap = dictDataMap
      this.isSetDict = true
      wsCache.set(CACHE_KEY.DICT_CACHE, dictDataMap, { exp: 60 }) // 60 秒 过期
      console.debug('字典数据已加载到内存并缓存到本地')
    },
    async setDictMap() {
      if (this.isSetDict) {
        console.debug('重用内存中的字典数据')
        return this.dictMap
      }
      const dictMap = wsCache.get(CACHE_KEY.DICT_CACHE)
      if (!dictMap) {
        console.debug('字典数据需要从远程获取')
        await this.loadDictData()
      } else {
        this.dictMap = dictMap
        this.isSetDict = true
        console.debug('字典数据从本地缓存读取')
      }
    },
    getDictByType(type: string) {
      if (!this.isSetDict) {
        this.setDictMap().then(() => {})
      }
      return this.dictMap[type]
    }
  }
})

export const useDictStoreWithOut = () => {
  return useDictStore(store)
}
